<template>
  <div>
    <el-form label-position="left" class="flow-config-attr" label-width="90px">
      <el-form-item label="触发时机">
        <el-select
          v-model="form.methods"
          class="input-attr"
          clearable
          placeholder="支持多选"
        >
          <el-option
            v-for="item in data.flowMethods"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事件处理器">
        <CommonSelect
          v-model:defaultValue="form.listenerId"
          placeholder="请选择事件处理器"
          autoQuery
          label="listenerName"
          value="id"
          url="/esflow/event/listener/getlist"
          @change="handleListenerChange"
          :width="300"
        />
      </el-form-item>
      <el-form-item label="处理器参数">
        <el-button
          type="primary"
          icon="circle-plus"
          @click="addOption"
          size="small"
          >添加参数</el-button
        >
        <div
          style="display: flex; justify-content: space-between"
          v-for="(option, i) in form.eventParams"
        >
          <el-input v-model="form.eventParams[i].key" />
          <el-input v-model="form.eventParams[i].value" />
          <el-button icon="Delete" @click="form.eventParams.splice(i, 1)" />
        </div>
      </el-form-item>
      <el-form-item label="事件条件">
        <el-button
          type="primary"
          @click="handleRuleEdit"
          size="small"
          icon="edit-pen"
          >编辑条件</el-button
        >
        <el-tooltip placement="top">
          <template #content>
            事件允许设置生效条件，用于控制在某种条件下才会执行
          </template>
          <el-icon style="margin-left: 10px"><QuestionFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="监听备注">
        <el-input v-model="form.remark" class="input-attr" type="textarea" />
      </el-form-item>
      <el-form-item label="监听排序">
        <el-input-number v-model="form.sort" class="input-attr" :min="1" />
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: center">
      <el-button
        type="primary"
        round
        style="width: 200px; margin-top: 10px; margin-bottom: 10px"
        @click="saveListenerEvent"
      >
        保存事件
      </el-button>
    </div>
    <el-drawer class="flow-drawer" :size="configWidth" v-model="editVisible">
      <template #header>
        <div>
          <el-icon style="margin-right: 10px"><Edit /></el-icon>
          编辑条件
        </div>
      </template>
      <RuleEdit
        ref="ruleRef"
        v-model="rule"
        :formItemList="props.formItemList"
        @confirm="handleRuleConfirm"
      />
    </el-drawer>
  </div>
</template>
<script setup lang="ts" name="ListenerEvent">
import { useMessage } from "@/hooks/message";
import { validateNull } from "@/utils/validate";
import { DIC_PROP } from "@/views/design/process/Dict";
import { getRandNodeId } from "@/utils/process";
import { onMounted, reactive, ref } from "vue";
import type { Rule } from "../../ProcessNodes";
import { createNodeListener } from "../../ProcessNodes";
import type { FormItemPerm } from "@/views/design/form/FormComponentMixin";
import RuleEdit from "./RuleEdit.vue";
import type {
  EventListener,
  RuleGroup
} from "@/views/design/process/ProcessNodes";

const props = defineProps({
  eventType: {
    type: String,
    default: "0"
  },
  listeners: {
    type: Array<EventListener>,
    default: []
  },
  formItemList: {
    type: Array as PropType<FormItemPerm[]>,
    default: [] as any[]
  }
});

const emits = defineEmits(["confirm"]);

const _value: any = defineModel();

const configWidth = ref(500);
const editVisible = ref(false);

const rule = reactive<Rule>({
  ruleType: "3",
  ruleCode: "",
  groupType: "0",
  groups: []
});

const form = reactive<EventListener>({
  code: "",
  listenerId: null,
  listenerName: "",
  methods: "",
  remark: "",
  sort: 1,
  eventType: props.eventType,
  eventParams: [],
  ruleCode: getRandNodeId(),
  groupType: "0",
  groups: []
});

const data = reactive({
  flowMethods: []
});

onMounted(() => {
  if (props.eventType === "0") {
    data.flowMethods = DIC_PROP.NODE_METHODS;
  } else if (props.eventType === "1") {
    data.flowMethods = DIC_PROP.FLOW_METHODS;
  } else if (props.eventType === "2") {
    data.flowMethods = DIC_PROP.JOB_METHODS;
  }
});

const init = (event?: EventListener) => {
  console.log("init", event);
  if (event && event.listenerId) {
    form.listenerId = event.listenerId;
    form.listenerName = event.listenerName;
    form.methods = event.methods;
    form.ruleCode = event.ruleCode;
    form.remark = event.remark;
    form.sort = event.sort;
    form.eventType = event.eventType;
    form.ruleCode = event.ruleCode;
    form.groupType = event.groupType;
    if (event.groups && event.groups.length > 0) {
      form.groups = event.groups;
    }
    if (event.eventParams && event.eventParams.length > 0) {
      form.eventParams = event.eventParams;
    }
    rule.ruleType = event.ruleType;
    rule.ruleCode = event.ruleCode;
    rule.groupType = event.groupType;
    rule.groups = event.groups;
  }
};

const reset = () => {
  form.listenerId = null;
  form.listenerName = "";
  if (props.eventType === "0") {
    form.methods = DIC_PROP.NODE_METHODS[0].value;
  } else if (props.eventType === "1") {
    form.methods = DIC_PROP.FLOW_METHODS[0].value;
  } else if (props.eventType === "2") {
    form.methods = DIC_PROP.JOB_METHODS[0].value;
  }
  form.remark = "";
  form.sort = 1;
  form.groupType = "0";
  form.groups = [];
  form.ruleCode = getRandNodeId();
  form.eventType = props.eventType;
  form.eventParams = [] as any[];
};

const handleListenerChange = (id, option) => {
  form.listenerName = option.listenerName;
};

function addOption() {
  form.eventParams.push({
    key: "参数名称",
    value: "参数值"
  });
}

const handleRuleEdit = () => {
  editVisible.value = true;
};

const handleRuleConfirm = eventrule => {
  editVisible.value = false;
  rule.ruleType = "3";
  rule.ruleCode = "";
  rule.groupType = "0";
  rule.groups = [] as RuleGroup[];
  form.ruleCode = eventrule.ruleCode;
  form.groupType = eventrule.groupType;
  form.groups = eventrule.groups;
};

const saveListenerEvent = () => {
  if (!form.listenerName) {
    useMessage().warning("请选择事件处理器");
    return;
  }
  if (validateNull(form.methods)) {
    useMessage().warning("触发时机不能为空");
    return;
  }
  const listenersList = props.listeners;
  const itemIndex = listenersList.findIndex(item => {
    return item.ruleCode === form.ruleCode;
  });
  if (itemIndex != -1) {
    listenersList[itemIndex].listenerId = form.listenerId;
    listenersList[itemIndex].listenerName = form.listenerName;
    listenersList[itemIndex].methods = form.methods;
    listenersList[itemIndex].remark = form.remark;
    listenersList[itemIndex].sort = form.sort;
    listenersList[itemIndex].eventParams = form.eventParams;
    listenersList[itemIndex].ruleCode = form.ruleCode;
    listenersList[itemIndex].groupType = form.groupType;
    listenersList[itemIndex].groups = form.groups;
  } else {
    const event = createNodeListener(props.eventType);
    event.listenerId = form.listenerId;
    event.listenerName = form.listenerName;
    event.methods = form.methods;
    event.remark = form.remark;
    event.sort = form.sort;
    event.eventParams = form.eventParams;
    event.ruleCode = form.ruleCode;
    event.groupType = form.groupType;
    event.groups = form.groups;
    listenersList.push(event);
  }
  console.log("listenersList", listenersList);
  form.groupType = "0";
  form.groups = [];
  reset();
  console.log("confirm", listenersList);
  emits("confirm", listenersList);
};

defineExpose({
  init,
  reset
});
</script>

<style lang="scss" scoped>
@use "@/assets/style/design/flow-attr.scss";
</style>
